
propsage.namespace("prestige.receipt");

prestige.receipt.create = (function($, ui){
	
	function initComponents() {
		
		$("#AddContactDlg").dialog({
			'width': 500,
			'autoOpen': false,
			'resizable': false,
			'modal': true,
			'buttons': {
				'Cancel': onDialogCancel,
				'OK': {
					'text': 'Add Contact',
					'class': 'blue',
					'click': onAddContactOK
				}
			},
			'open': onAddContactOpen
		});
	}
	
	function initEventHandlers() {   
		$('#btAddContact').click(function() {
			$("#AddContactDlg").dialog("open");
		});
	}
	
	function onAddContactOpen() {
	/* copy input name into dlg? */
	}
	
	function onAddContactOK() {
		var isValid = false,
		data = null,
		href = null;
		
		isValid = $('#add-contact-form').yiiactiveform2("validate");

		if(isValid) {
			data = $("#add-contact-form").serializeArray();
			href = $("#add-contact-form").attr("action");
			ui.growl('Saving...', 'loading');
			ui.doAjax('post', href, data, onAddContactSuccess);
			$('#AddContactDlg').dialog("close");
		}
	}
	
	function onAddContactSuccess(response) {
		ui.growl('Contact added.');
		if(response['name'] !== null) {
			$("#Receipt_payer_name").val(response['name']);
			$("#Receipt_payer_party_id").val(response['party_id']);
			$("#Receipt_contact_id").val(response['id']);
		}
		
		if(response['id'] !== null) {
			$("#Receipt_contact_id").val(response['id']);
		}
	}
	
	
	function onDialogCancel() {
		$(this).dialog("close");
	}
    
	
	$(document).ready(function(){
		initComponents();
		initEventHandlers();
	});
    
}(jQuery, propsage.ui));